<?php
/*--------------------------
	file:	upload.class
	intro:	上传文件类
--------------------------*/

/*
	upload.class.php
	牛行网上传类
	功能：单文件上传，缩略图生成，水印生成，批量上传，批量缩略图，批量水印，中文水印。
	说明：$up = new Upload; 
		上传：$up->UP($_FILES['fileinput']); 
		缩略图：($up->toFile=true;//可生成文件，否则直接显示!)
				$up->makeThumb($filepath|$filepath_array);
		水印：($up->toFile=true;同上!)
			$up->makeWMark([$filepath|$filepath_array], array("网站名（中英文）","网址(英文)"))
	备注：上传的文件保存在默认的文件夹 ROOT/upload/ 下，并按年月自动生成文件夹存放，缩略图保存在年月文件夹下一级的thumb文件夹，水印在mark文件夹
*/
class Helper_Upload extends Base{
  var $_object;         	//文件对象
  var $_upPath;       	  	//上传文件的保存路径(必须以"/"结尾)
  var $_curname;      		//当前上传的图片名称
  var $_allowExt;       	//允许上传的文件类型
  var $_maxSize;        	//允许上传的大小
  var $_log;                //上传日志
  var $_namearray;         	//上传成功的新文件名
  var $_fontType;			//英文字体位置
  var $_cnFontType;			//中文字体位置
  var $_waterImg;			//水印图片,设计图片背景透明，保存为PNG24格式！
  var $_error;
  var $_result;
  var $_cid;

  //构造函数(上传对象， 上传路径， 允许大小， 新名称， 允许扩展名)
	function Helper_Upload(){
		//
	}
	//初始化上传对象
	function Up($_object){
		!is_array($_object) && $this->Error("上传对象未设置", "echo");
		$this->_object = $_object;
		$this->_curname = "";
		$this->_log = "";
		$this->_namearray = array();
	}
	
	function _set($arr=array()){
		global $customdir;
		$this->_upPath = !$arr['path'] ? DDIR."upload/" : $arr['path'];
		$this->_maxSize = !$arr['size'] ? 1024*1024*2 : $arr['size'];
		$this->_allowExt = !$arr['ext'] ? "jpg/gif/png/doc/rar/zip" : $arr['ext'];
		$this->_fontType = !$arr['enfont'] ? $customdir."/font/04B_08__.TTF" : $arr['enfont'];
		$this->_cnFontType = !$arr['cnfont'] ? $customdir."font/msyhbd.ttf" : $arr['cnfont'];
		$this->_waterImg = !$arr['img'] ? $customdir."waterimg/x.png" : $arr['img'];
		$this->setPath($arr['subpath']);		
	}
	
	function _debug(){
		$str = $this->_sprint($this->_error);
		$str.= $this->_sprint($this->_log);
		$str.= $this->_sprint($this->_result);
		$this->_debugshow($str);
	}
	
		//设置上传路径
	function setPath($path=""){
		if($path != ''){
			$this->_upPath = $this->_upPath.$path;
		}else{
			$upChild = date("Ym")."/";
			$this->_upPath = $this->_upPath.$upChild;
		}
		//echo $this->_upPath;
		!is_dir($this->_upPath) && mkdir($this->_upPath);
	}
	
	//获取上传文件的扩展名
	function getFileExt($filename){
		//echo $filename;
		$pos = strrpos($filename,".");
		if($pos === false){
			$this->Error($filename."文件格式不正确");
			//continue;
			return false;
		}
		$ext_name = substr($filename,$pos+1);
		//echo $ext_name;
		return strtolower($ext_name);
	}
	


	//检测要上传的文件是否符合要求
	function checkAndUpload(){
		if(!is_array($this->_object["name"])){
			$this->_cid = '0';
			$this->setR('upload', 0);
			$this->setR('name', $this->_object["name"]);
			$this->_curname = $this->_object["name"];
			$fileext = $this->getFileExt($this->_curname);
			if(!$fileext){
				return false;
			}
			$filesize = $this->_object["size"];
			if(strpos($this->_allowExt, $fileext) === false){
				$this->Error($this->_curname."是不合法的文件类型\n");
				$this->setR('error', '不是合法的文件类型');
				//$this->result[0]['']
			}elseif($filesize > $this->_maxSize){
				$this->Error($this->_curname."的大小超过限制\n");
				$this->setR('error', '大小超过限制');
			}else{
				$this->uploadFile($this->_object['tmp_name'], $fileext);
			}
		}else{//批量上传
			for($i = 0; $i < count($this->_object["name"]); $i++){
				$this->_cid = $i;
				$this->setR('upload', 0);
				$this->setR('name', $this->_object["name"][$i]);
				if($this->_object["name"][$i] == ''){
					continue;
				}
				$this->_curname = $this->_object["name"][$i];
				$fileext = $this->getFileExt($this->_curname);
				if(!$fileext)return false;
				$filesize = $this->_object["size"][$i];
				
				if(strpos($this->_allowExt,$fileext) === false){
					$this->Error($this->_curname."是不合法的文件类型");
					$this->setR('error', '不是合法的文件类型');
				}elseif($filesize > $this->_maxSize){
					$this->Error($this->_curname."的大小超过限制");
					$this->setR('error', '大小超过限制');
				}else{
					$this->uploadFile($this->_object['tmp_name'][$i], $fileext);
				}
			}
		}
	}

  //上传函数
	function uploadFile($tmpname, $fileext){
		$ran = rand();  //产生随机数
		$newname = date("YmdHis").$ran.".".$fileext;
		if(file_exists($newname)){
			$this->Error($this->_curname."与其他文件名冲突\n");
			$this->setR('error', '文件名冲突');
			return false;
		}
		if(@move_uploaded_file($tmpname, $this->_upPath.$newname)){
			$this->setR('upload', 1);
			$this->setLog($this->_curname."于".date('Y-m-d H:i:s')."成功上传到".$this->_upPath.$newname);
			$this->_namearray[] = $newname;
			return true;
		}
		return false;
	}
	
	function makeThumb($photo,$width=160,$height=160){
		if(empty($photo))return false;
		if(is_array($photo)){
			foreach($photo as $k=>$p){
				$photo[$k] = $this->_upPath.$p;
			}
		}else{
			$photo = $this->_upPath.$photo;
		}
		$path = $this->_upPath."thumb/";
		$this->smallImg($photo, $path ,$width, $height);
	}
	
	function makeWMark($photo,$text){
		if(empty($photo))return false;
		if(is_array($photo)){
			foreach($photo as $k=>$p){
				$photo[$k] = $this->_upPath.$p;
			}
		}else{
			$photo = $this->_upPath.$photo;
		}
		$path = $this->_upPath."mark/";
		$this->waterMark($photo, $path ,$text);
	}
  
	function smallImg($photo, $_thumbPath, $width=200, $height=200) {
  		if(is_array($photo)){
			foreach($photo as $p){
				$this->smallImg($p,$_thumbPath,$width,$height);
				//next;
			}
		}else{
			//$photo = $this->_upPath.$photo;//获得图片源
			$imgInfo = $this->getInfo($photo);
			
			if($imgInfo["type"] == 1) {
					$img = imagecreatefromgif($photo);
					$ext = "gif";
			} elseif($imgInfo["type"] == 2) {
					$img = imagecreatefromjpeg($photo);
					$ext = "jpg";
			} elseif($imgInfo["type"] == 3) {
					$img = imagecreatefrompng($photo);
					$ext = "png";
			} else {
					$img = "";
			}			
			if(empty($img)) return False;
			$newName = "thumb_".substr($imgInfo["name"],0,strrpos($imgInfo["name"], ".")).".".$ext;//新图片名称
			
			$width = ($width > $imgInfo["width"]) ? $imgInfo["width"] : $width; 
			$height = ($height > $imgInfo["height"]) ? $imgInfo["height"] : $height; 
			$srcW = $imgInfo["width"]; 
			$srcH = $imgInfo["height"]; 
			if ($srcW * $width > $srcH * $height) {
					$height = round($srcH * $width / $srcW);
			}else{
					$width = round($srcW * $height / $srcH);
			}
			if (function_exists("imagecreatetruecolor")) {
					$newImg = imagecreatetruecolor($width, $height);
					$bgc = imagecolorallocate($newImg, 200, 210, 210);
					imagefilledrectangle($newImg, 0, 0, $width, $height, $bgc);	//设置背景色
					ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
			}else{
					$newImg = imagecreate($width, $height);
					$bgc = imagecolorallocate($newImg, 200, 210, 210);
					imagefilledrectangle($newImg, 0, 0, $width, $height, $bgc);	//设置背景色
					ImageCopyResized($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
			}
			if ($this->toFile){
				//$_thumbPath = $this->_upPath."thumb/";
				!is_dir($_thumbPath) && @mkdir($_thumbPath);
				$_thumbFilePath = $_thumbPath.$newName; 
				if(file_exists($_thumbFilePath)) @unlink($_thumbFilePath);
				
				if($imgInfo["type"] == 1) {
					imagegif($newImg, $_thumbFilePath);
				} elseif($imgInfo["type"] == 2) {
					imagejpeg($newImg, $_thumbFilePath);
				} elseif($imgInfo["type"] == 3) {
					imagepng($newImg, $_thumbFilePath);
				}
				//ImageJPEG($newImg, $_thumbFilePath);
				//return $_thumbFilePath;
			}else{
				if($imgInfo["type"] == 1) {
					imagegif($newImg);
				} elseif($imgInfo["type"] == 2) {
					imagejpeg($newImg);
				} elseif($imgInfo["type"] == 3) {
					imagepng($newImg);
				}
				//ImageJPEG($newImg);
			}
			ImageDestroy($newImg);
			ImageDestroy($img);
			return true;
		}
		return false;
	}

	function waterMark($photo,$_markPath,$text){
		if(is_array($photo)){
			foreach($photo as $p){
				$this->waterMark($p,$_markPath,$text);
			}
		}else{
			//$photo = $this->_upPath.$photo;
			$imgInfo = $this->getInfo($photo);
			
			//print_r($imgInfo);
			//exit;
			switch ($imgInfo["type"]) {
				case 1:
						$img = imagecreatefromgif($photo);
						$ext = "gif";
				break;
				case 2:
						$img = imagecreatefromjpeg($photo);
						$ext = "jpg";
				break;
				case 3:
						$img = imagecreatefrompng($photo);
						$ext = "png";
				break;
				default:
						return False;
			}
			if (empty($img)) return False;
			$newName = substr($imgInfo["name"], 0, strrpos($imgInfo["name"], ".")) . "_mark.".$ext;
			//$width = ($this->maxWidth > $imgInfo["width"]) ? $imgInfo["width"] : $this->maxWidth; 
			//$height = ($this->maxHeight > $imgInfo["height"]) ? $imgInfo["height"] : $this->maxHeight; 
			$width = $imgInfo["width"];
			$height= $imgInfo["height"];
			$srcW = $imgInfo["width"]; 
			$srcH = $imgInfo["height"]; 
			if ($srcW * $width > $srcH * $height) {
					$height = round($srcH * $width / $srcW);
			} else {
					$width = round($srcW * $height / $srcH);
			}
			if (function_exists("imagecreatetruecolor")) {
					$newImg = imagecreatetruecolor($width, $height);
					$bgc = imagecolorallocate($newImg, 200, 210, 210);
					imagefilledrectangle($newImg, 0, 0, $width, $height, $bgc);	//设置背景色
					ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
			} else {
					$newImg = imagecreate($width, $height);
					$bgc = imagecolorallocate($newImg, 200, 210, 210);
					imagefilledrectangle($newImg, 0, 0, $width, $height, $bgc);	//设置背景色
					ImageCopyResized($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
			}
			
			if(is_array($text)){
				$white = imageColorAllocate($newImg, 255, 255, 255);
				$black = imageColorAllocate($newImg, 30, 30, 30);
				$alpha = imageColorAllocateAlpha($newImg, 230, 230, 230, 40);
				ImageFilledRectangle($newImg, 0, $height-26, $width, $height, $alpha);
				ImageFilledRectangle($newImg, 13, $height-20, 15, $height-7, $black);
				ImageTTFText($newImg, 9, 0, 20, $height-14, $black, $this->_cnFontType, $text[0]);
				ImageTTFText($newImg, 4.9, 0, 20, $height-5, $black, $this->_fontType, $text[1]);
			}else{//使用图片水印
				$wInfo = $this->getInfo($this->_waterImg);
				switch($text){//方位选择
					case 0:
						$des_x = ($imgInfo["width"]-$wInfo["width"])/2;
						$des_y = ($imgInfo["height"]-$wInfo["height"])/2;
					break;
					case 1:
						$des_x = 0;
						$des_y = 0;
					break;
					case 2:
						$des_x = $imgInfo["width"]-$wInfo["width"];
						$des_y = 0;
					break;
					case 3:
						$des_x = $imgInfo["width"]-$wInfo["width"];
						$des_y = $imgInfo["height"]-$wInfo["height"];
					break;
					case 4:
						$des_x = 0;
						$des_y = $imgInfo["height"]-$wInfo["height"];
					break;
					default:
						$des_x = 0;	$des_y = 0;
				}
				$simage1 =imagecreatefrompng($this->_waterImg); 
				imagecopy($newImg,$simage1,$des_x,$des_y,0,0,$wInfo["width"],$wInfo["height"]); 
				imagedestroy($simage1); 
			}
			if($this->toFile){
				//$_markPath = $this->_upPath."mark/";//水印文件夹
				!is_dir($_markPath) && @mkdir($_markPath);
				if (file_exists($_markPath.$newName)) @unlink($_markPath.$newName);
				if($imgInfo["type"] == 1) {
					imagegif($newImg, $_markPath.$newName);
				} elseif($imgInfo["type"] == 2) {
					imagejpeg($newImg, $_markPath.$newName);
				} elseif($imgInfo["type"] == 3) {
					imagepng($newImg, $_markPath.$newName);
				}
					//ImageJPEG($newImg, $_markPath.$newName);
					//return $this->upFolder."/".$this->markFolder."/".$newName;
			} else {
					//ImageJPEG($newImg);
				if($imgInfo["type"] == 1) {
					$img = imagegif($newImg);
				} elseif($imgInfo["type"] == 2) {
					$img = imagejpeg($newImg);
				} elseif($imgInfo["type"] == 3) {
					$img = imagepng($newImg);
				}
			}
			ImageDestroy($newImg);
			ImageDestroy($img);
			return true;
		}
		return false;
	}
  //记录上传日志
	function setLog($log){
	   $this->_log[] = $log;
	}
	  
	function getInfo($photo) {

		$imageInfo = getimagesize($photo);
		$imgInfo["width"] = $imageInfo[0];
		$imgInfo["height"] = $imageInfo[1];
		$imgInfo["type"] = $imageInfo[2];
		$imgInfo["name"] = basename($photo);
		return $imgInfo;
	}
	function setR($name, $value){
		$this->_result[$this->_cid][$name] = $value;
	}
  //错误提示
	function Error($msg,$type='return'){
		switch($type){
			case 'alert':
				echo "<script>alert('$msg');history.go(-1)</script>";
				break;
			case 'echo':
				echo $msg;
				break;
			case 'return':
				$this->_error[] = $msg;
				break;
		}
		return false;
		//exit;
	}
}
?>
